package com.mc.main;

import java.net.SocketException;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 
 * ListActivity to let the user pick a Arduino unit
 * and select if he/she wants to control it or
 * view the sensors
 * 
 * @Author Mikael Bertlin
 *
 */

public class UnitPicker extends ListActivity implements OnItemClickListener {
	
	static final String[] UNITS = new String[] {
		"Dummy1", "Dummy2", "Dummy3", "Dummy4", "Dummy5"
	};
	
	private final CharSequence[] items = {"Control", "Monitor"};
	private AlertDialog.Builder builder;
	
	public void onCreate(Bundle savedInstanceState) {
		
		 super.onCreate(savedInstanceState);
		 
		 setContentView(R.layout.up_layout);
	     setListAdapter(new ArrayAdapter<String>(this, R.layout.up_row, R.id.label, UNITS));
	     getListView().setTextFilterEnabled(true);
		 getListView().setOnItemClickListener(this);
		 builder = new AlertDialog.Builder(this);
		 
		if(UdpClient.client == null){
			try {
				UdpClient.client = new UdpClient(UdpClient.HOST, UdpClient.PORT);
			} catch (SocketException e) {
				// TODO Auto-generated catch block
				Log.v("UdpClient", e.getMessage());
			}
		}else{
			Log.v("UdpClient", "UdpClient already created, skipping...");
		}
	}

	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		
		builder.setTitle(UNITS[position]);
		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				if(item == 0){
					Intent myInt = new Intent(UnitPicker.this, ControllerDummy.class);
					startActivity(myInt);	
				} else if(item == 1){
					Intent myInt = new Intent(UnitPicker.this, SimpleGraphStart.class);
					startActivity(myInt);
				}
				Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}
}
